#coding=utf-8
import datetime
from google.appengine.ext import db

def relate(a, b):

    r = Related.all().filter('a', a).filter('b', b).get()
    if r: return
    
    Related(a=a, b=b).put()
    Related(a=b, b=a).put()
    
class Article(db.Model):

    md5 = db.StringProperty(required=True)
    title = db.StringProperty(required=True)
    
    authors = db.StringListProperty()   
    journal = db.StringProperty()
    pub_date = db.DateProperty()
    abstract = db.StringProperty()
 
    category = db.StringProperty()
    url = db.LinkProperty()
    
    def get_related(self):
        articles = []
        for r in self.related_set:
            articles.append(r.b)
        return articles
        
    def add_related(self, b):
        relate(self, b)

class Related(db.Model):
    a = db.ReferenceProperty(Article)
    b = db.ReferenceProperty(Article, collection_name="related_articles")

class ArticleFile(db.Model):
    uuid = db.StringProperty(required=True)
    
    a = db.ReferenceProperty(Article, required=True)
    a_type = db.StringProperty(required=True, choices=set(["caj", "pdf"]))
    
    original_url = db.LinkProperty()
    a_server = db.IntegerProperty()
    
